package com.xyyl.patient.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayBaseRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.common.collect.Maps;
import com.xyyl.patient.common.utils.SysConfigUtils;
import com.xyyl.patient.core.constant.AppEnum;
import com.xyyl.patient.core.controller.BaseController;
import com.xyyl.patient.core.exception.BusinessException;
import com.xyyl.patient.core.support.Pager;
import com.xyyl.patient.core.util.DateUtils;
import com.xyyl.patient.core.util.ResponseBodyResult;
import com.xyyl.patient.core.util.StringUtils;
import com.xyyl.patient.entity.doctor.Disease;
import com.xyyl.patient.entity.doctor.Doctor;
import com.xyyl.patient.entity.mall.MallOrderInfo;
import com.xyyl.patient.entity.mall.MallUserAddress;
import com.xyyl.patient.entity.question.Prescription;
import com.xyyl.patient.entity.user.ActivityUser;
import com.xyyl.patient.service.archives.ArchivesService;
import com.xyyl.patient.service.doctor.DoctorService;
import com.xyyl.patient.service.mall.MallOrderInfoService;
import com.xyyl.patient.service.mall.MallUserAddressService;
import com.xyyl.patient.service.order.ConsultOrderService;
import com.xyyl.patient.service.order.PhoneOrderService;
import com.xyyl.patient.service.order.SpeedPhoneOrderService;
import com.xyyl.patient.service.user.*;
import com.xyyl.patient.vo.GraphConsultMiniVo;
import com.xyyl.patient.vo.IMVo;
import com.xyyl.patient.vo.user.AccountRecordVo;
import com.xyyl.patient.vo.user.UserVo;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chengjun
 * @ClassName: UserCenterController
 * @Description: 个人中心Controller
 * 1.个人资料
 * 2.我的服务
 * 3.我的医生
 * 4.我的处方
 * 5.我的账户明细
 * 6.意见反馈
 * @date 2017年8月16日
 */
@RestController
@RequestMapping("/userCenter")
public class UserCenterController extends BaseController {

    private Logger logger = LogManager.getLogger(UserCenterController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityUserService activityUserService;
    @Autowired
    private AccountRecordService accountRecordService;

    @Autowired
    private MyserviceService myserviceService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private MallUserAddressService mallUserAddressService;

    @Autowired
    private MallOrderInfoService mallOrderInfoService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ArchivesService archivesService;

    @Autowired
    private PhoneOrderService phoneOrderService;

    @Autowired
    private SpeedPhoneOrderService speedPhoneOrderService;

    @Autowired
    private ConsultOrderService consultOrderService;
    @Autowired
    private WxPayService payService;

    @Value("#{weixin['common.domain']}")
    private String domain;

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: queryDetail
     * @Description: 个人中心，获取用户详细资料
     */
    @RequestMapping(value = "/queryDetail", method = RequestMethod.GET)
    public JSONObject queryDetail(@RequestParam Integer userid) {
        logger.info(" query userid:{}", userid);
        try {
            UserVo userVo = userService.queryUserDetailById(userid);
            if (userVo != null) {
                userVo.setAccountbalance(
                        userVo.getAccountbalance() == null ? new BigDecimal("0.00") : userVo.getAccountbalance());
                userVo.setNickname(StringUtils.encode(userVo.getNickname()));
                if (userVo.getMobile() != null) {
                    userVo.setMobile("1");
                } else {
                    userVo.setMobile("0");
                }
            }
            return ResponseBodyResult.success(userVo);
        } catch (BusinessException e) {
            return ResponseBodyResult.error("个人资料查询失败!", e);
        }
    }

    /**
     * @param @param  patientid
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: myDoctorList
     * @Description: 我的医生列表
     */
    @RequestMapping(value = "/myDoctorList", method = RequestMethod.POST)
    public JSONObject myDoctorList(@RequestParam Integer patientid) {
        try {
            List<Map<String, Object>> myDorctorList = new ArrayList<Map<String, Object>>();
            List<Doctor> doctorList = userService.queryUserDoctorList(patientid);
            // 获取最新关注医生的信息
            if (doctorList != null && doctorList.size() > 0) {
                for (Doctor doctor : doctorList) {
                    Map<String, Object> mapResult = new HashMap<String, Object>();
                    if (StringUtils.isEmpty(doctor.getAvatar())) {
                        String defaultDoctor = SysConfigUtils
                                .getConfigValue(AppEnum.sysConfig.DOCTOR_AVATAR_ALIYUN_URL.name());
                        doctor.setAvatar(defaultDoctor);
                    }

                    List<Disease> diseaseList = doctorService.getDiseaseByDoctorId(doctor.getId());
                    mapResult.put("diseaseList", diseaseList);
                    mapResult.put("doctor", doctor);
                    myDorctorList.add(mapResult);
                }
            }
            return ResponseBodyResult.success(myDorctorList);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  patientid
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: myPrescriptionList
     * @Description: 我的处方单列表
     */
    @RequestMapping(value = "/myPrescriptionList", method = RequestMethod.GET)
    public JSONObject myPrescriptionList(@RequestParam Integer patientid) {
        try {
            List<Prescription> prescriptionList = userService.queryUserPrescriptionList(patientid);
            if (prescriptionList.size() > 0 & prescriptionList != null) {
                for (int i = 0; i < prescriptionList.size(); i++) {
                    Doctor doctor = doctorService.getDoctorById(prescriptionList.get(i).getDoctoruserId());
                    if (doctor != null) {
                        prescriptionList.get(i).setDoctorName(doctor.getRealname());
                    }

                }
            }
            return ResponseBodyResult.success(prescriptionList);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  patientid
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: myPrescriptionList
     * @Description: 我的处方单列表
     */
    @RequestMapping(value = "/getOnePrescription", method = RequestMethod.GET)
    public JSONObject getOnePrescription(@RequestParam Integer id) {
        try {
            Prescription prescriptionList = userService.queryUserPrescription(id);
            if (prescriptionList != null) {
                prescriptionList.setDoctorName(doctorService.getDoctorById(prescriptionList.getDoctoruserId()).getRealname());
            }
            return ResponseBodyResult.success(prescriptionList);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: myServiceList
     * @Description: 我的服务列表
     */
    @RequestMapping(value = "/myServiceList", method = RequestMethod.GET)
    public JSONObject myServiceList(@RequestParam Integer userid, @RequestParam Integer typeOrder) {
        logger.info(" query patientid:{}", userid);
        Pager pager = super.initPage();
        try {
            List<GraphConsultMiniVo> myServiceList = myserviceService.queryUserServiceList(pager, typeOrder);
            logger.info(" myServiceListSize", myServiceList.size());
            if (myServiceList != null && !myServiceList.isEmpty()) {
                pager.setData(myServiceList);
            }
            return ResponseBodyResult.success(pager);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: myServiceInfo
     * @Description: 我的服务详情
     */
    @RequestMapping(value = "/myServiceInfo", method = RequestMethod.GET)
    public JSONObject myServiceInfo(@RequestParam Integer id, @RequestParam Integer typeOrder) {
        try {
//            if(typeOrder ==1){
//                QuickQuestion myServiceList = myserviceService.quickQuestionInfo(id);
//                Archives archives =null;
//                if(myServiceList!=null){
//                    archives = archivesService.selectOne(myServiceList.getArchivesid());
//                }
//               Map map = new HashMap();
//                map.put("myServiceList",myServiceList);
//                map.put("archives",archives);
//
//                return ResponseBodyResult.success(map);
//            }else if(typeOrder==3) {
//                return ResponseBodyResult.success(phoneOrderService.queryOrderDetailById(id));
//            }else if(typeOrder==4) {
            Map<String, Object> objectMap = speedPhoneOrderService.queryInfo(id, typeOrder);
            return ResponseBodyResult.success(objectMap);
//            }else {
//                GraphConsultMiniVo myServiceList = myserviceService.queryUserServiceInfo(id, typeOrder);
//                return ResponseBodyResult.success(myServiceList);
//            }


        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: getPharmacyInfo
     * @Description: 最近的藥店的詳情
     */
    @RequestMapping(value = "/getPharmacyInfo", method = RequestMethod.GET)
    public JSONObject getPharmacyInfo(@RequestParam Integer id) {
        Map<String, Object> objectMap = null;
        objectMap = myserviceService.getPharmacyInfo(id);
        return ResponseBodyResult.success(objectMap);
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: myAccount
     * @Description: 我的账户明细
     */
    @RequestMapping(value = "/myAccount", method = RequestMethod.GET)
    public JSONObject myAccount(@RequestParam Integer userid) {

        Pager pager = super.initPage();
        List<AccountRecordVo> accountRecordVos = null;

        try {
            accountRecordVos = accountRecordService.queryUserAccountRecoreList(pager);
            if (accountRecordVos != null && !accountRecordVos.isEmpty()) {
                pager.setData(accountRecordVos);
            }

            return ResponseBodyResult.success(pager);

        } catch (Exception e) {
            return ResponseBodyResult.error("账户明细查询失败!", e);

        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: feedback
     * @Description:问题反馈
     */
    @RequestMapping(value = "/feedback", method = RequestMethod.POST)
    public JSONObject feedback(Long id) {

        return ResponseBodyResult.success("OK");
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: feedback
     * @Description:是否是新用户
     */
    @RequestMapping(value = "/getIsNewPatient", method = RequestMethod.GET)
    public JSONObject getIsNewPatient(@RequestParam Integer id) {
        try {
            ActivityUser activityUser = activityUserService.getActivityUser(id);
            if (activityUser == null) {
                return ResponseBodyResult.success("恭喜你可以领取奖励", 1);
            }
            return ResponseBodyResult.success("您已经领取过奖励了", 0);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    @RequestMapping(value = "/getNewPatientRedPacket", method = RequestMethod.POST)
    public JSONObject getNewPatientRedPacket(@RequestParam Integer id) {
        try {
            Integer result = activityUserService.getNewPatientRedPacket(id);
            if (result == 1) {
                return ResponseBodyResult.success("领取成功", result);
            } else {
                return ResponseBodyResult.success("领取失败", result);
            }

        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    @RequestMapping(value = "/getIndexIM", method = RequestMethod.GET)
    public JSONObject getIndexIM(@RequestParam Integer id) {
        try {
            List<IMVo> imVoList = userService.getIndexIM(id);
            return ResponseBodyResult.success("查询成功", imVoList);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  uid
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: getUserAddress
     * @Description:查询意见购药用户地址
     */
    @RequestMapping(value = "/getUserAddress", method = RequestMethod.POST)
    public JSONObject getUserAddress(@RequestBody MallUserAddress mallUserAddress) {
        try {
            List<MallUserAddress> mallUserAddressList = mallUserAddressService.queryList(mallUserAddress);
            return ResponseBodyResult.success("查询成功", mallUserAddressList);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  uid
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: addUserAddress
     * @Description:添加 购药地址
     */
    @RequestMapping(value = "/addUserAddress", method = RequestMethod.POST)
    public JSONObject addUserAddress(@RequestBody MallUserAddress mallUserAddress) {
        try {
            Integer result = mallUserAddressService.saveMallUserAddress(mallUserAddress);
            return ResponseBodyResult.success("添加成功", result);
        } catch (Exception e) {
            return ResponseBodyResult.error("添加失败!", e);
        }
    }

    /**
     * @param @param  uid
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: updateUserAddress
     * @Description:添加 修改地址
     */
    @RequestMapping(value = "/updateUserAddress", method = RequestMethod.POST)
    public JSONObject updateUserAddress(@RequestBody MallUserAddress mallUserAddress) {
        try {
            Integer result = mallUserAddressService.updateMallUserAddress(mallUserAddress);
            return ResponseBodyResult.success("修改成功", result);
        } catch (Exception e) {
            return ResponseBodyResult.error("修改失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: deleteUserAddress
     * @Description:添加 删除地址
     */
    @RequestMapping(value = "/deleteUserAddress", method = RequestMethod.POST)
    public JSONObject deleteUserAddress(@RequestParam Integer id) {
        try {
            Integer result = mallUserAddressService.deleteMallUserAddress(id);
            return ResponseBodyResult.success("删除成功", result);
        } catch (Exception e) {
            return ResponseBodyResult.error("删除失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: addMallOrderInfo
     * @Description:新增购药订单
     */
    @RequestMapping(value = "/addMallOrderInfo", method = RequestMethod.POST)
    public JSONObject addMallOrderInfo(@RequestParam Integer id, @RequestParam String openId, @RequestParam Integer addrId) {
        try {
            MallOrderInfo mallOrderInfo = new MallOrderInfo();
            mallOrderInfo.setPrescriptionId(id);
            mallOrderInfo.setOpenId(openId);
            mallOrderInfo.setUserId(addrId);//为了传参
            Integer result = mallOrderInfoService.saveMallOrderInfo(mallOrderInfo);
            HashMap hm = new HashMap();
            hm.put("id", result);
            return ResponseBodyResult.success("下单成功", hm);
        } catch (Exception e) {
            return ResponseBodyResult.error("下单失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: getOrderActivity
     * @Description:获取购药优惠
     */
    @RequestMapping(value = "/getOrderActivity", method = RequestMethod.GET)
    public JSONObject getOrderActivity(@RequestParam Integer id) {
        try {
            return ResponseBodyResult.success("最新优惠", activityService.getActivity(id));
        } catch (Exception e) {
            return ResponseBodyResult.error("失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: updateMallOrderList
     * @Description:查看购药订单
     */
    @RequestMapping(value = "/updateMallOrderList", method = RequestMethod.POST)
    public JSONObject updateMallOrderList(@RequestBody MallOrderInfo mallOrderInfo) {
        try {
            Integer result = mallOrderInfoService.updateMallOrderInfo(mallOrderInfo);
            return ResponseBodyResult.success("修改成功", result);
        } catch (Exception e) {
            return ResponseBodyResult.error("修改失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: getMallOrderList
     * @Description:查看购药订单
     */
    @RequestMapping(value = "/getMallOrderList", method = RequestMethod.POST)
    public JSONObject getMallOrderList() {
        Pager pager = super.initPage();
        try {
            List<MallOrderInfo> mallOrderInfoList = mallOrderInfoService.queryList(pager);
            return ResponseBodyResult.success("查询成功", mallOrderInfoList);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }

    /**
     * @param @param  id
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: getMallOrderList
     * @Description:查看购药订单
     */
    @RequestMapping(value = "/getOneMallOrder", method = RequestMethod.POST)
    public JSONObject getOneMallOrder(@RequestParam Integer id) {
        try {
            MallOrderInfo mallOrderInfo = mallOrderInfoService.queryObject(id);
            //mallOrderInfo.setAddTime (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateUtils.stampToDate(mallOrderInfo.getAddTime().getTime())));
            return ResponseBodyResult.success("查询成功", mallOrderInfo);
        } catch (Exception e) {
            return ResponseBodyResult.error("查询失败!", e);
        }
    }


    /**
     * @return 返回类型
     * @throws
     * @Title: confirmPay
     * @Description: 确认支付(购药)
     * 一、微信支付：1.调用微信统一下单接口，返回JSSDKPayInfo相关的信息
     */
    @RequestMapping(value = "/confirmPay", method = RequestMethod.POST)
    public JSONObject confirmPay() {
        //userId=74&id=0
        Pager pager = super.initPage();
        logger.info("---confirmPay  payOrder---");
        try {
            MallOrderInfo mallOrderInfo = mallOrderInfoService.queryList(pager).get(0);
            if (mallOrderInfo.getPayStatus().equals(0)) {
                return submitWxPay(mallOrderInfo);
            } else {
                return ResponseBodyResult.fail("该订单已付款");
            }

        } catch (Exception e) {

            return ResponseBodyResult.error("订单提交支付失败!", e);
        }
    }

    /**
     * @return JSONObject  返回类型
     * @throws
     * @Title: submitWxPay
     * @Description:提交微信统一下单
     */
    private JSONObject submitWxPay(MallOrderInfo mallOrderInfo) {
        /** 组装参数信息 **/
        WxPayUnifiedOrderRequest prepayInfo = WxPayUnifiedOrderRequest.newBuilder()
                .openid(mallOrderInfo.getOpenId())
                .outTradeNo(mallOrderInfo.getOrdersn())
                .totalFee(WxPayBaseRequest.yuanToFee(String.valueOf(mallOrderInfo.getOrderAmount())))
                .body("购药订单支付")
                .spbillCreateIp("192.168.0.1")
                .notifyURL(domain + "/userCenter/orderPayCallback")
                .build();

        /** 提交微信统一下单 **/
        Map<String, String> payInfos = Maps.newHashMap();
        try {
            payInfos = this.payService.getPayInfo(prepayInfo);

            if (payInfos != null && payInfos.get("package") != null) {
                return ResponseBodyResult.success("统一下单成功", payInfos);
            } else {
                return ResponseBodyResult.fail("统一下单失败");
            }
        } catch (WxPayException e) {
            return ResponseBodyResult.error("统一下单失败", e);
        }

    }

    /**
     * @param request
     * @param response
     * @return String    返回类型
     * @throws
     * @Title: orderPayCallback
     * @Description: 微信通知支付结果的回调并更新订单信息
     */
    @RequestMapping(value = "/orderPayCallback", method = RequestMethod.POST)
    public String orderPayCallback(HttpServletRequest request, HttpServletResponse response) {

        logger.info("---callback  payOrder---");
        try {
            synchronized (this) {
                /** 解析支付结果 **/
                String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
                WxPayOrderNotifyResult result = payService.parseOrderNotifyResult(xmlResult);
                if (AppEnum.common.Pay_result_success.getName().equals(result.getReturnCode())) {
                    if (AppEnum.common.Pay_result_success.getName().equals(result.getResultCode())) {

                        /** 支付成功，处理业务数据 **/
                        String ordersn = result.getOutTradeNo();
                        //String ordersn = "GY-20180328141245033";
                        Pager pager = super.initPage();
                        pager.getPageData().put("ordersn", ordersn);

                        List<MallOrderInfo> mallOrderInfoList = mallOrderInfoService.queryList(pager);
                        if (mallOrderInfoList == null) {
                        } else {
                            if (mallOrderInfoList.get(0).getPayStatus().equals(AppEnum.common.Pay_status_not.getValue())) {
                                MallOrderInfo mallOrderInfo = new MallOrderInfo();
                                mallOrderInfo.setId(mallOrderInfoList.get(0).getId());
                                mallOrderInfo.setPayStatus(AppEnum.common.Pay_status_confirm.getValue());
                                mallOrderInfo.setPayTime(DateUtils.getSysTimestamp());
                                mallOrderInfoService.updateMallOrderInfo(mallOrderInfo);
                                //更新处方单状态
                                Prescription prescription = new Prescription();
                                prescription.setId(mallOrderInfoList.get(0).getPrescriptionId());
                                prescription.setIsbuy(AppEnum.common.Pay_status_confirm.getValue());
                                mallOrderInfoService.updatePrescription(prescription);

                            }
                        }
                        return WxPayNotifyResponse.success("ok");
                    } else {
                        return WxPayNotifyResponse.fail("result_code is FAIL");
                    }
                } else {
                    return WxPayNotifyResponse.fail("check signature FAIL");
                }

            }
        } catch (Exception e) {
            return WxPayNotifyResponse.fail("http request FAIL");
        }

    }

}
